import React, {Component} from 'react'
import { InputItem, Toast } from 'antd-mobile'
import propTypes from 'prop-types'
import {addClass} from '../common/js/utils'

class CInput extends Component {

  onErrorClick = () => {
    const { name } = this.props
    const { getFieldError } = this.props.form
    const error = getFieldError(name)
    if (error) {
      Toast.info(error.join(','))
    }
  }

  render() {
    let { children, form, name, rules, trigger, className } = this.props
    const { getFieldProps, getFieldError } = form
    if (rules.some(item => item.required)) {
      className = addClass(className || '', 'required')
    }
    return (
      <InputItem
        {...this.props}
        {...getFieldProps(name, {rules, validateTrigger: trigger})}
        error={!!getFieldError(name)}
        onErrorClick={this.onErrorClick}
        className={className}
      >{children}</InputItem>
    )
  }
}

CInput.propsTypes = {
  trigger: propTypes.string,
  name: propTypes.string,
  form: propTypes.object,
  rules: propTypes.array
}

CInput.defaultProps = {
  trigger: 'onChange',
  rules: []
}

export default CInput
